﻿using System;
using RuTracker.Interface;

namespace RuTracker.MVC.Core
{
    public class SettingsDataContext
    {
        public SettingsDataContext(User user
            , UserStorageInfo userStorage
            , DropboxAdapter dropBoxService)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            DropboxService = dropBoxService;
            User = user;
            UserStorage = userStorage;
        }

        public DropboxAdapter DropboxService { get; private set; }
        public UserStorageInfo UserStorage { get; private set; }
        public User User { get; private set; }

        public void SetFolder(string folder)
        {
            EnsureStorageExists();

            UserStorage.StorageFolder = folder;
        }

        public void SetToken(byte[] token)
        {
            EnsureStorageExists();

            UserStorage.Token = token;
        }

        private void EnsureStorageExists()
        {
            if (UserStorage == null)
                UserStorage = new UserStorageInfo();
        }

        public string StorageFolder 
        {
            get { return UserStorage != null ? UserStorage.StorageFolder : string.Empty; }
        }

        public bool IsLoginRequired
        {
            get { return UserStorage == null || UserStorage.Token == null; }
        }

        public bool IsFolderSelectionRequired
        {
            get { return !IsLoginRequired && string.IsNullOrEmpty(UserStorage.StorageFolder); }
        }

        public bool IsSaveAvailable
        {
            get { return !IsLoginRequired && !IsFolderSelectionRequired; }
        }

        public void Save()
        {
            IUserRepository userRepository = Container.Current.Resolve<IUserRepository>();
            userRepository.UpdateUser(User);

            if (UserStorage != null)
                userRepository.SetUserStorageInfo(User.Name, UserStorage.StorageFolder, UserStorage.Token != null ? UserStorage.Token.ToArray() : null);
        }
    }
}